package org.springcloud.plugin.framework.strategy.isolation;

import ch.qos.logback.core.spi.ContextAware;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springcloud.plugin.common.constant.DiscoveryConstant;
import org.springcloud.plugin.common.util.StringUtil;
import org.springcloud.plugin.framework.listener.BasicListener;
import org.springcloud.plugin.framework.listener.register.RegisterListener;
import org.springcloud.plugin.framework.strategy.constant.StrategyConstant;
import org.springframework.cloud.client.serviceregistry.Registration;

import java.util.List;

/**
 * @Author yanggld
 * @Date 2020/2/4-20:11
 * @Description
 */
public class IsolationRegisterStrategy extends BasicListener implements RegisterListener {

	@Override
	public void onRegister(Registration registration) {
		String serviceId = coreAdapter.getServiceId();
		String host = coreAdapter.getHost();
		int port = coreAdapter.getPort();
		String group = coreAdapter.getGroup();

		List<String> groupWhitelist = getGroupWhitelist();
		if (CollectionUtils.isNotEmpty(groupWhitelist) && !groupWhitelist.contains(group)) {
			onRegisterFailure(group, serviceId, host, port, false);
		}
	}

	protected List<String> getGroupWhitelist() {
		String groupWhitelistText = pluginContextAware.getEnvironment().getProperty(StrategyConstant.SPRING_APPLICATION_STRATEGY_REGISTER_ISOLATION_GROUP_WHITELIST, String.class, null);
		if (StringUtils.isEmpty(groupWhitelistText)) {
			return null;
		}
		return StringUtil.splitToList(groupWhitelistText, DiscoveryConstant.SEPARATE);
	}

	private void onRegisterFailure(String group, String serviceId, String host, int port, boolean isBlacklist) {
		String description = serviceId + " for " + host + ":" + port + " is rejected to register to Register server, it's group=" + group;
		if (isBlacklist) {
			description += " is in isolation blacklist";
		} else {
			description += " isn't in isolation whitelist";
		}
		throw new RuntimeException(description);
	}

	@Override
	public void onDeregister(Registration registration) {

	}

	@Override
	public void onSetStatus(Registration registration, String status) {

	}
}
